<template>
    <div v-if="title" class="title">
        {{ title }}
    </div>
    <div class="tag-list">
        <tag v-if="showLimit" class="mb" label="不限" :value="0" :is-checked="!selection.length" @click="handleClick({ label: '不限', value: 0 })">
        </tag>
        <template v-for="(item, index) in props.data" :key="index">
            <tag class="mb" :label="item[props.label]" :value="item[props.value]" :is-checked="isChecked(item)" @click="handleClick(item)">
            </tag>
        </template>
    </div>
</template>

<script lang="ts" setup>
import { PropType, ref, watch, onMounted } from 'vue';
import tag from './tags.vue';

interface Tag{
    [key: string]: string | number,
}

const props = defineProps({
    // 标签列表标题
    title: {
        type: String,
        default: ''
    },
    // 是否支持多选
    isMultiple: {
        type: Boolean,
        default: false
    },
    // 自定义标签文本字段
    label: {
        type: String,
        default: 'label',
    },
    // 自定义标签值字段
    value: {
        type: String,
        default: 'value',
    },
    // 标签列表数据
    data: {
        type: Array as unknown as PropType<Tag[]>,
        default: () => []
    },
    // 已选中的标签列表数据
    selectionData: {
        type: Array as unknown as PropType<Tag[]>,
        default: () => []
    },
    // 是否显示不限
    showLimit: {
        type: Boolean,
        default: false
    },
    isDisabled: {
        type: Boolean,
        default: false
    }
});

const emit = defineEmits(['click']);

const selection = ref<Tag[]>([]);

const isChecked = (item: Tag) => {
    return selection.value.some((selectItem) => selectItem[props.value] === item[props.value]);
};

const handleClick = (item: Tag) => {
    if (props.isDisabled) {
        return;
    }
    selection.value = JSON.parse(JSON.stringify(props.selectionData)) as Tag[];
    if (props.isMultiple) {
        if (item.label === '不限') {
            selection.value = [];
        } else if (selection.value.some((selectItem) => selectItem[props.value] === item[props.value])) {
            selection.value = selection.value.filter((selectItem) => selectItem[props.value] !== item[props.value]);
        } else {
            selection.value.push(item);
        }
    } else {
        selection.value = [item];
    }
    emit('click', selection.value);
};
watch(
    () => props.selectionData,
    (newVal) => {
        selection.value = newVal;
    },
    { deep: true }
);
onMounted(() => {
    selection.value = props.selectionData;
});
</script>

<style lang="scss" scoped>
.title {
    font-size: 13px;
    font-weight: 600;
    color: #333333;
    margin-bottom: 8px;
}
.mb {
    margin-bottom: 12px;
}
.tag-list {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
}
.tag-list > *:not(:nth-child(3n)) {
    margin-right: 12px;
}
</style>
